/**
 * Copyright 2011 Mathieu Magnaudet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package edu.enac.geoapp.wims.model;

import java.util.ArrayList;
import java.util.List;

import org.geotools.geometry.jts.JTSFactoryFinder;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;

/**
 * Java bean to encapsulate a list of points describing 2 closed polygons
 * 
 * @author mathieu
 * 
 */
public class PolygonBuilder {
	private List<LinearRing> holes;
	private LinearRing exteriorPoints;
	private GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
	private Polygon polygon = null;
	
	/**
	 * @param interiorPoints the interiorPoints to set
	 */
	public void addHole(List<Point> interiorPoints) {
		Coordinate coords[] = new Coordinate[interiorPoints.size()];
		int coordIndex = 0;
			for(Point p: interiorPoints) {
				coords[coordIndex++] = new Coordinate(p.getLatitude(), p.getLongitude());
			}
		LinearRing ring = geometryFactory.createLinearRing(coords);
		this.holes.add(ring);
	}

	/**
	 * @param exteriorPoints the exteriorPoints to set
	 */
	public void setExteriorPoints(List<Point> exteriorPoints) {
		Coordinate coords[] = new Coordinate[exteriorPoints.size()];
		int coordIndex = 0;
			for(Point p: exteriorPoints) {
				coords[coordIndex++] = new Coordinate(p.getLatitude(), p.getLongitude());
			}
		this.exteriorPoints = geometryFactory.createLinearRing(coords);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Area [holes=" + holes + ", exteriorPoints="
				+ exteriorPoints + "]";
	}

	

	
	public PolygonBuilder() {
		holes = new ArrayList<LinearRing>();
	}
	
	/**
	 * @return the interior points
	 */
	public List<LinearRing> getHoles() {
		return holes;
	}

	/**
	 * 
	 * @return the exterior points
	 */
	public LinearRing getExteriorPoints() {
		return exteriorPoints;
	}

	public void buildPolygon() {
		LinearRing rings[] = new LinearRing[holes.size()];
		int i = 0;
		for(LinearRing ring: holes) {
			rings[i++] = ring;
		}
		polygon = geometryFactory.createPolygon(exteriorPoints, rings);
	}
	
	public Polygon getPolygon() {
		return polygon;
	}
}
